package de.openkanban.server.interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import de.openkanban.server.interceptor.annotation.SecurityInterception;
import de.openkanban.server.session.OpenKanbanSessionAttributes;

@Interceptor
@SecurityInterception
@Component
public class SecurityInterceptor {

	@Autowired
	private OpenKanbanSessionAttributes sessionAttributes;

	@AroundInvoke
	public Object validateSession(InvocationContext ctx) throws Exception {
		Object[] params = ctx.getParameters();

		HttpServletRequest req = null;
		HttpServletResponse resp = null;

		for (Object param : params) {
			if (param instanceof HttpServletRequest) {
				req = (HttpServletRequest) param;
			} else if (param instanceof HttpServletResponse) {
				resp = (HttpServletResponse) param;
			}
		}

		if (req == null || sessionAttributes.getUserId(req) == null) {
			if (resp != null) {
				resp.setStatus(401);
			}

			return null;
		}

		return ctx.proceed();
	}

	public void setSessionAttributes(OpenKanbanSessionAttributes sessionAttributes) {
		this.sessionAttributes = sessionAttributes;
	}

}
